<?php

namespace app\meizhuangapi\service\order;
use app\factory\MqFactory;
use app\common\model\Wxapp as WxappModel;
use think\Hook;
use think\Db;
use app\meizhuangapi\model\User as UserModel;
use app\common\service\goods\source\Factory as StockFactory;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\model\SingleOrder as SingleOrderModel;
use app\meizhuangapi\model\dealer\Referee as RefereeModel;
use app\meizhuangapi\model\dealer\Order as DealerOrderModel;

use app\api\service\order\PaySuccess as PaySuccessCon;
/**
 * 订单支付成功服务类
 * Class PaySuccess
 * @package app\api\service\order
 */
class PaySuccess extends PaySuccessCon
{
    /**
     * 订单支付成功业务处理
     * @param $payType 10 余额支付 20 微信支付
     * @param array $payData
     * @return bool
     */
    public function onPaySuccess($payType, $payData = [])
    {
        $this->mysicLog->setFilename('notify/order');
        if (empty($this->model)) {
            $this->error = '未找到该订单信息';
            $this->mysicLog->info($payType, '支付类型');
            $this->mysicLog->info(json_encode($payData), '支付数据');
//            $this->log('未找到订单信息: ' . '类型 - ' . $payType, json_encode($payData));
            return false;
        }

        $this->mysicLog->info([
            '订单ID' => $this->model->order_id, '用户id'=>$this->model->user_id, '订单编号' => $this->model->order_no,'商品总金额(不含优惠折扣)' => $this->model->total_price,
            '订单金额(含优惠折扣)' => $this->model->order_price, '实际付款金额(包含运费)' => $this->model->pay_price, '后台修改的订单金额（差价）' =>  $this->model->pay_price,
            '支付方式(10余额支付 20微信支付)' => $this->model->pay_type['value'], '付款状态(10未付款 20已付款)' => $this->model->pay_status['value'],'付款时间' =>$this->model->pay_time,
            '订单状态(10进行中 20取消 21待取消 30已完成)'=>$this->model->order_status['value'], '订单来源(10普通订单 20砍价订单 30秒杀订单 40购买会员订单 50当面付订单)' => $this->model->order_source,
            '是否为虚拟物品(1是 2不是)' => $this->model->is_fictitious,'分红与否(0未分红 1已份红)'=>$this->model->is_abouns
        ], '订单信息');

        // 更新付款状态
        $this->mysicLog->info('', '开始更新订单状态');
        $status = $this->updatePayStatus($payType, $payData);
        $this->mysicLog->info(bool2str($status), '更新订单状态是否成功');
        $order = db('order')->where('order_no',$this->model->order_no)->find();
        $this->mysicLog->info($order, '更新后的订单信息');
        // 订单支付成功行为
        if ($status == true) {
            $this->mysicLog->info('', '订单支付状态更新成功，准备入队列');
            $this->mysicLog->info('开始', '执行hook');
            try {
                Hook::listen('order_pay_success', $this->model, OrderTypeEnum::MASTER);
            } catch(\Exception $e) {
                $this->mysicLog->error(exceptionLogFormat($e), '订单支付成功调用Hook抛出异常');
            }
            $this->mysicLog->info('开始', '判断是否满足入队列条件');
            $this->mysicLog->info(bool2str($this->model['pay_type']['value'] == 20), '支付类型是否是微信支付');
            $this->mysicLog->info(bool2str(bcmul($this->model['pay_price'], '100') >= 1), '支付金额是否大于1分钱');
            $this->mysicLog->info(bool2str($this->model['is_fictitious'] == 1), '订单是否为虚拟物品');
            $this->mysicLog->info(bool2str(!empty($order['transaction_id'])), '订单transaction_id是否不为空');
            if($this->model['pay_type']['value'] == 20 && bcmul($this->model['pay_price'], '100') >= 1 && $this->model['is_fictitious'] == 1 ){
                if(!empty($order['transaction_id'])) {
                    //订单支付时间
                    $rem = MqFactory::instance();
                    $data=['orderId'=> $this->model['order_id'],'time'=>time()];
                    $this->mysicLog->info($data, '成功订单入队列');
                    $rem->send($data,'userListData','userListDataLog','userListDataLog');
                }
            }

        }
        return $status;
    }

    /**
     * 更新付款状态
     * @param $payType
     * @param array $payData
     * @return bool
     */
    private function updatePayStatus($payType, $payData = []){
        // 验证余额支付时用户余额是否满足
        if ($payType == PayTypeEnum::BALANCE) {
            //验证收益余额和储值余额 郭涛
            $money=Db::name('dealer_user')->where(['user_id'=>$this->user['user_id']])->find();
            if (($this->user['money'] < $this->model['pay_price'])&&($money['money']<$this->model['pay_price'])) {
                $this->mysicLog->error(['用户余额' => $this->user['money'], '支付金额' => $this->model['pay_price']],'用户余额不足，无法使用余额支付');
                return false;
            }
        }
        $result = false;
        try{
            if($this->model['order_source']==50) {
                $result = $this->updateFaceOrderInfo($payType, $payData);
            } elseif($this->model['order_source']==10) {
                $result = $this->updateOrderInfo($payType, $this->model,$payData);
            }elseif($this->model['order_source']==30){
                //更新秒杀订单支付状态  add 郭涛
                $result = $this->updateMiaoShaOrderInfo($payType,$payData,$this->model);
            }
            // 事务处理
//          $this->model->transaction(function () use ($payType, $payData) { //此处不用事务，避免其他入库操作失败导致订单更新失败
            //累积用户总消费金额
            $this->mysicLog->info($this->model['pay_price'], '累加用户总消费金额');
            $this->user->setInc('pay_money', $this->model['pay_price']);
            //更新用户最大订单记录表
            $orderData['amount'] = $this->model['pay_price'];
            $orderData['pay_type'] = $payType;
            $orderData['wxapp_id'] = $this->model['wxapp_id'];
            $orderData['user_id'] = $this->model['user_id'];
            $this->mysicLog->info($orderData, '更新用户最大订单记录表');
            SingleOrderModel::updateData(['wxapp_id'=>$this->model['wxapp_id'],'user_id'=>$this->model['user_id']],$orderData);
            $this->mysicLog->info(null, '更新用户最大订单记录表结束');
            //判断用户是否有上级，有则进行分销处理
            $this->mysicLog->info('开始', '判断用户是否有上级，有则进行分销处理');
            $upuserId = RefereeModel::isExistReferee($this->model['user_id']);
            $this->mysicLog->info($upuserId, '用户上级ID');
            $upuserInfo = UserModel::detail($upuserId);
            //当面付订单
            if($this->model['order_source']==50 ){
                $this->mysicLog->info('开始', '更新当面付订单');
                if($this->model['pay_type']['value']==20){
                    $this->mysicLog->info('微信支付', '当面付订单支付方式');
                    $this->mysicLog->info(bool2str($result), '更新面对面支付订单结果');
                    //查看商户设置的分销方案  206
                    $dealer_case = WxappModel::dealerCase($this->model['wxapp_id']);
                    if ($upuserId) {
                        $checkDealeModel = new UserModel;
                        if ($dealer_case == 1) {
                            $checkDealer = $checkDealeModel->getConfigByUserType($upuserInfo, $type = "face");
                            if ($checkDealer) {
                                $this->mysicLog->info($checkDealer, '获取分销方案1配置');
                                if ($checkDealer['consume_charge'] > 0) {
                                    //配置百分比大于0
                                    DealerOrderModel::createFaceOrder($this->model, $checkDealer['consume_charge'], $upuserId, $upuserInfo['wxapp_id'], 50, 10, $dealer_case);
                                }
                            }
                        } elseif ($dealer_case = 2) {
                            $checkDealer = $checkDealeModel->getDealerTow($upuserInfo, $type = "face_status");
                            $this->mysicLog->info($checkDealer, '获取分销方案2配置');
                            if ($checkDealer) {
                                DealerOrderModel::createFaceOrder($this->model, $checkDealer, $upuserId, $upuserInfo['wxapp_id'], 50, 10, $dealer_case);
                            }
                        }
                    }
                    $this->mysicLog->info(bool2str($result), '更新面对面支付订单结果');
                }
            }elseif($this->model['order_source']==10){
                $this->mysicLog->info('开始', '更新普通订单');
                DealerOrderModel::grantMoney($this->model,10,50);
            }
            // 记录订单支付信息
            //$this->updatePayInfo($payType);
//            });
        } catch(\Exception $e) {
            $result = false;
            $this->mysicLog->error(exceptionLogFormat($e), '更新订单状态抛异常');
        }
        $this->mysicLog->info(bool2str($result), '订单状态更新结果');
        return $result;
    }

    /**
     * 更新订单记录
     * @param $payType
     * @param $payData
     * @return false|int
     * @throws \Exception
     */
    private function updateOrderInfo($payType, $order,$payData)
    {

        // 更新商品库存、销量
        StockFactory::getFactory($this->model['order_source'])->updateStockSales($this->model['goods']);

        $time = time();
        // 整理订单信息
        $upData =[
            'pay_type' => $payType,//支付方式
            'pay_status' => 20,//付款状态(10未付款 20已付款)
            'pay_time' => $time//付款时间
        ];

        //虚拟商品
        if($order['is_fictitious']==1){
            $upData['order_status'] = 30;//订单状态(10进行中 20取消 21待取消 30已完成)
            $upData['delivery_status'] = 20;//发货状态(10未发货 20已发货)
            $upData['delivery_time'] = $time;//发货时间
            $upData['receipt_status'] = 20; //收货状态(10未收货 20已收货)
            $upData['receipt_time'] = $time;//收货时间
            $upData['delivery_type'] = 20;//配送方式(10快递配送 20上门自提)
            $upData['is_settled'] = 1;//订单是否已结算(0未结算 1已结算)
        }
        $upData['transaction_id'] = $payData['transaction_id'] ?? '';
        // 更新订单状态
        return $this->model->isUpdate(true)->save($upData);
    }


    private function updateFaceOrderInfo($payType, $payData)
    {
        $time = time();
        // 整理订单信息
        $order =[
            'pay_type'       => $payType,//支付方式
            'pay_status'     => 20,//付款状态(10未付款 20已付款)
            'pay_time'       => $time,//付款时间
            'order_status'   => 30,//订单状态(10进行中 20取消 21待取消 30已完成)
            'delivery_status' => 20,//发货状态(10未发货 20已发货)
            'delivery_time'   => $time,//发货时间
            'receipt_status'  =>20,//收货状态(10未收货 20已收货)
            'receipt_time'  =>$time,//收货时间
            'delivery_type'  =>30,//配送方式(10快递配送 20上门自提 30当面付)
            'is_settled'  =>1,//订单是否已结算(0未结算 1已结算)
        ];
        // $this->log('更新订单状态 - 回调transaction', $payData['transaction_id']);
        $this->log('更新订单状态 - payType', $payType);
        $order['transaction_id'] = $payData['transaction_id'] ?? '';
        $this->log('更新订单状态 - order', $order);

        // 更新订单状态
        return $this->model->save($order);
    }
    private function updateMiaoShaOrderInfo($payType, $payData,$mo){
        $time = time();
        // 整理订单信息
        $order =[
            'pay_type'       => $payType,//支付方式
            'pay_status'     => 20,//付款状态(10未付款 20已付款)
            'pay_time'       => $time,//付款时间
            'order_status'   => 10,//订单状态(10进行中 20取消 21待取消 30已完成)
            'delivery_status' => 10,//发货状态(10未发货 20已发货)
            'delivery_time'   => 0,//发货时间
            'receipt_status'  =>10,//收货状态(10未收货 20已收货)
            'receipt_time'  =>0,//收货时间
            'is_settled'  =>1,//订单是否已结算(0未结算 1已结算)
        ];
        //更新订单状态
        return $this->model->isUpdate(true)->save($order);
    }



    /**
     * 记录订单支付信息
     * @param $payType
     * @throws \think\Exception
     */
    private function updatePayInfo($payType)
    {
        // 余额支付
        if ($payType == PayTypeEnum::BALANCE) {
            // 更新用户余额
            $this->mysicLog->info('','余额支付 - 开始减扣用户余额...');
            $result = $this->user->setDec('money', $this->model['pay_price']);
            $this->mysicLog->info($result,'减扣用户余额结果');
            MoneyLogModel::add([
                'scene'=>Scene::CONSUME,
                'user_id' => $this->user['user_id'],
                'money' => -$this->model['pay_price'],
                'order_no' => $this->model['order_no'],
            ]);
            $this->mysicLog->info([
                '余额变动场景(10用户购买会员卡充值 20退款 30用户消费 40管理员操作)'=>Scene::CONSUME,
                '用户ID' => $this->user['user_id'],
                '减扣金额' => $this->model['pay_price'],
                '订单号' => $this->model['order_no'],
            ],'余额减扣计入用户余额消费流水');
        }
        // 微信支付
        if ($payType == PayTypeEnum::WECHAT) {
            // 更新prepay_id记录
//            WxappPrepayIdModel::updatePayStatus($this->model['order_id'], OrderTypeEnum::MASTER);
        }
    }






}